import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/ai/ai_pay_entity.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/tip_widget.dart';
import '../../../controller/pick/ai_pay_logic.dart';
import '../../../resources/colours.dart';
import '../../../resources/styles.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../../../widgets/base/qkd_button.dart';

class AiPayPage extends StatefulWidget {
  const AiPayPage({Key? key}) : super(key: key);

  @override
  State<AiPayPage> createState() => _AiPayPageState();
}

class _AiPayPageState extends State<AiPayPage> {
  final AiPayLogic logic = Get.put(AiPayLogic());
  @override
  Widget build(BuildContext context) {
    return GetBuilder<AiPayLogic>(builder: (logic) {
      return PopScope(
        canPop: false,
        onPopInvoked: (didPop) async {
          if(didPop) return;
          Get.back(result: true);
        },
        child: Scaffold(
          backgroundColor: Colours.greyF2F3F7,
          appBar: Styles.appBar(
            backgroundColor: Colours.transparent,
            title: QkdText(logic.type?.name??""),
            titleTextStyle: const TextStyle(
              color: Colours.text,
              fontSize: 18,
              fontWeight: FontWeight.w500),
            onTapLeading: () => Get.back(result: true)
          ),
          body: SizedBox(
            height: Get.height,
            child: LoadingWidget<bool>(
              isLoading: logic.data == null,
              data: logic.price == null,
              child: () => Stack(
                children: [
                  SingleChildScrollView(
                    physics: const ClampingScrollPhysics(),
                    child: Padding(
                      padding: const EdgeInsets.only(bottom: 140),
                      child: Column(
                        children: [
                          if(logic.info != null)
                          Block(
                            cardStyle: const CardStyle(
                              margin: EdgeInsets.fromLTRB(12, 10, 12, 0),
                              padding: EdgeInsets.all(16)),
                            child: _aiInfo()),
                          if(logic.price.hasValue)
                          Block(
                            cardStyle: const CardStyle(
                              margin: EdgeInsets.fromLTRB(12, 10, 12, 0),
                              padding: EdgeInsets.symmetric(vertical: 12)),
                            child: _subscribeChoice()),
                          if (logic.tip.hasValue)
                            Block(
                              cardStyle: const CardStyle(
                                margin: EdgeInsets.fromLTRB(12, 10, 12, 0),
                                padding: EdgeInsets.fromLTRB(12, 12, 12, 20)),
                              child: _notice())
                        ],
                      ),
                    ),
                  ),
                  Positioned(bottom: 0, left: 0, right: 0, child: _payBar())
                ],
              ),
            ),
          ),
        ),
      );
    });
  }

  Widget _aiInfo(){
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        QkdImage(imageUrl: logic.info?.logo, width: 44, height: 44),
        Container(width: 14),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            QkdText(logic.info?.name ?? "", fontSize: 16),
            Container(height: 2),
            QkdText(logic.info?.info ?? "", color: Colours.grey99),
          ],
        )
      ]
    );
  }

  Widget _subscribeChoice() {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(height: 10),
      if(logic.benefits?.length.hasValue == true)
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: List.generate(
          logic.benefits?.length ?? 0,
          (index) => Expanded(child: _benefit(logic.benefits![index]))
        ),
      ).paddingOnly(bottom: 20,top: 14,left: 10,right: 10),
      SizedBox(
        height: 136,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 1),
          itemExtent: (Get.width-58)/3 + 7,
          scrollDirection: Axis.horizontal,
          children: List<Widget>.generate(
            logic.price?.length ?? 0,
            (index) => _price(index).paddingOnly(right: 7)
          ),
        ),
      ),
      Container(height: 10)
    ]);
  }

  Widget _notice() {
    return Column(
      children: [
        QkdText("购买须知",
          fontSize: 16,
          fontWeight: FontWeight.w500
        ),
        Container(height: 16),
        const TipWidget(
          type: "ai_pay_tip",
          fontSize: 14,
          lineHeight: 1.6,
          textColor: Colours.grey66
        )
      ],
    );
  }

  Widget _payBar() {
    AiPrice? price = logic.price.hasValue == true?(logic.price?[logic.priceIndex]):null;
    return Column(
      children: [
        Container(
          color: Colors.white,
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          child: Row(
            children: [
              QkdText(
                  logic.realPrice[logic.priceIndex] != 0.0?"${logic.realPrice[logic.priceIndex]}球币":price?.price == "0球币" ? "限时免费" : price?.price ?? "",
                fontSize: 16,
                color: Colours.main,
                fontWeight: FontWeight.w500
              ),
              Container(width: 4),
              if(logic.realPrice[logic.priceIndex] != 0.0)
                QkdText((price?.price ?? "").changeUnit,
                  fontSize: 12,
                  decoration: TextDecoration.lineThrough,
                  color: Colours.grey99
                ),
              const Spacer(),
              QkdButton(
                width: 108,
                height: 40,
                onPressed: () {
                  Utils.onEvent('aixq_zfyd');
                  if (price?.price.noValue != true) {
                    logic.toPay(price!);
                  }
                },
                borderRadius: 20,
                backgroundColor: Colours.main,
                foregroundColor: Colours.white,
                text: "立即支付",
                textStyle:
                    const TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
              )
            ],
          ),
        ),
        Container(
            color: Colours.white, height: MediaQuery.of(context).padding.bottom)
      ],
    );
  }

  Widget _benefit(AiBenefit benefit) {
    return Column(
      children: [
        CachedNetworkImage(
          fit: BoxFit.cover,
          width: 40,
          height: 40,
          imageUrl: benefit.logo ?? "",
          placeholder: (context, url) => Container(),
          errorWidget: (context, url, error) => Container()),
        QkdText(benefit.name ?? "",
          fontWeight: FontWeight.w600,
          textAlign: TextAlign.center
        ).paddingOnly(top: 4, bottom: 2),
        QkdText(benefit.info ?? "",
          fontSize: 12, color: Colours.grey99,
          textAlign: TextAlign.center)
      ],
    );
  }

  Widget _price(int index) {
    var price = logic.price?[index];
    var align = Alignment.center;
    if (index == 0) align = Alignment.centerLeft;
    if (index == 2) align = Alignment.centerRight;
    return GestureDetector(
      onTap: () => logic.onChange(index),
      child: SizedBox(
        height: 135,
        child: Stack(
          alignment: AlignmentDirectional.topCenter,
          children: [
            Container(
              height: 132,
              alignment: align,
              clipBehavior: Clip.antiAlias,
              decoration: BoxDecoration(
                  color: logic.priceIndex == index
                    ? Colours.main.withOpacity(0.05) : Colours.white,
                border: Border.all(
                  color: logic.priceIndex != index?Colours.redFDD9D9:Colours.main,
                  width: logic.priceIndex != index?0.5:1,
                  strokeAlign: BorderSide.strokeAlignOutside),
                borderRadius: BorderRadius.circular(8)),
              child: Column(
                children: [
                  Container(
                    width: Get.width,
                    height: 28,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: logic.priceIndex != index
                            ? Colours.redFFF4F4
                            : Colours.main.withOpacity(0.2)),
                    child: QkdText(price?.days ?? "")
                  ),
                  SizedBox(
                    width: Get.width,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(height: 16),
                        price?.price == "0球币"?
                        const QkdText("限时免费",
                          fontWeight: FontWeight.w500,
                          fontSize: 20,
                          color: Colours.redBD2929
                        ): Text.rich(
                          TextSpan(
                            style: const TextStyle(
                              fontWeight: FontWeight.w500,
                              fontSize: 20,
                              color: Colours.redBD2929
                            ),
                            children: [
                              TextSpan(
                                text: price?.price?.split("球币").join().trim() ?? ""
                              ),
                              TextSpan(
                                text: "球币".changeUnit,
                                style: const TextStyle(fontSize: 12)
                              )
                            ]
                          )
                        ),
                        if(price?.content.hasValue == true)
                        Container(
                          margin: const EdgeInsets.only(top: 10),
                          padding: const EdgeInsets.symmetric(horizontal: 6,vertical: 2),
                          decoration: BoxDecoration(
                              color: logic.priceIndex != index
                                  ? const Color(0xFFFFF4F4)
                                  : const Color(0xFFFEE7E7),
                              borderRadius: BorderRadius.circular(15)),
                          child: QkdText(price?.content ?? "",
                              needCenter: true,
                              fontSize: 10,color: Colours.grey66
                          )
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
            if(price?.tag.hasValue == true)...[
              Positioned(
                  bottom: 0,
                  child: Image.asset(height: 19,Utils.getImgPath("ai_discount_back.png"))),
              Positioned(
                  bottom: 0,
                  child: Container(
                    height: 19,
                    alignment: Alignment.center,
                    child: QkdText(price?.tag ?? "",
                      fontSize: 10,color: Colours.white
                    ),
                  ))
            ]
          ],
        ),
      ),
    );
  }
}
